package com.after.saas.common.utils;

import lombok.experimental.UtilityClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;

import java.util.concurrent.TimeUnit;

/**
 * 编码生成
 * @Created by hjchen
 */

@UtilityClass
public class CodeGenerateUtil {

    /**
     * 字符串补足方法
     *
     * @param length
     * @param currentValue
     * @return
     */
    public static String getCurrentValueString(Integer length, Integer currentValue) {
        String cValue = String.valueOf(currentValue);
        for (int i = cValue.length(); i < length; i++) {
            cValue = "0" + cValue;
        }
        return cValue;
    }


    public static String getSerialNumByBusiness(RedisTemplate redisTemplate, String... str) {
        String key = RedisUtil.redisCodeKey(str[0],str[1], LocalDateUtil.currentDateM());
        Integer code = incr(redisTemplate, key, -1, TimeUnit.MILLISECONDS);
        StringBuilder builder = new StringBuilder(str[1]);
        builder.append(LocalDateUtil.currentDateStr());
        builder.append(CodeGenerateUtil.getCurrentValueString(3, code));
        return builder.toString();
    }

    /**
     * 增加一个自动递增的key
     * @param redisTemplate
     * @param key
     * @return
     */
    public static Integer incr(RedisTemplate redisTemplate, String key, long time, TimeUnit timeUnit) {
        RedisAtomicInteger entityIdCounter = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
        int increment = entityIdCounter.incrementAndGet();
        /** //初始设置过期时间 **/
        boolean isExists = (increment==0) && time > 0;
        if (isExists) {
            entityIdCounter.expire(time, timeUnit);
        }
        return increment;
    }

}
